//
//  DownLoad.m
//  DoewloadDemo
//
//  Created by xalo on 16/6/17.
//  Copyright © 2016年 朱旭东. All rights reserved.
//

#import "DownLoad.h"
@interface DownLoad()<NSURLSessionDownloadDelegate>
@property (nonatomic,copy) DownLoading downLoading;
@property(nonatomic,copy)Complted  completed;
@end
@implementation DownLoad



- (NSURLSession *)session
{
    if (!_session) {
        _session = [NSURLSession  sessionWithConfiguration:[NSURLSessionConfiguration  defaultSessionConfiguration] delegate:self delegateQueue:nil];
    }
    return _session;
}

//重写init方法，在初始化的时候就去创建一个下载任务
- (instancetype)initWithUrl:(NSString*)url
{
    self = [super init];
    if (self) {
        //创建一个下载任务
    self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:url]];
    }
    return self;
}

//开始下载
- (void)startDownLoad{
    [self.task  resume];
}

//暂停下载
- (void)stopDownLoad{
    [self.task  suspend];
}

//正在下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

    if (self.downLoading) {
            self.downLoading (bytesWritten,totalBytesWritten * 100/(float)totalBytesExpectedToWrite);
    }
    
}


//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
 
    NSLog(@"%@",location.path);
    //我们要存放下载文件的路径
    NSString *filepath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES).lastObject;
    
    //拼接文件的名字，名字是从服务器上下载下来的
    NSString *fileName = downloadTask.response.suggestedFilename;
    filepath = [filepath  stringByAppendingString:fileName];
    
    //文件管理器,把临时的文件移到缓存文件夹下
    [[NSFileManager  defaultManager] moveItemAtPath:location.path toPath:filepath error:nil];

    if (self.completed) {
            self.completed(filepath,@"网址");
    }
    
}

//下载的时候和下载完成会走的方法
- (void)downLoading:(DownLoading)downloading didfinished:(Complted)complted{
    self.downLoading = downloading;
    self.completed = complted;
}

@end
